package com.finalproject.ui;
/**
 * Expense ExpenseSummary class for UI
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GradientPaint;
import java.util.Calendar;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import org.jfree.ui.*;
import org.jfree.chart.*;
import org.jfree.data.category.*;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import com.finalproject.entity.CardHolder;
import com.finalproject.entity.CardHolderDatabase;
import com.finalproject.entity.CardHolderDatabase.CardHolderDatabaseObserver;
import com.finalproject.entity.ExpenseEntry;
import com.finalproject.entity.ExpenseProfile;
import com.finalproject.entity.ExpenseProfile.ExpenseProfileObserver;

public class UIExpenseSummary extends JPanel implements CardHolderDatabaseObserver, ExpenseProfileObserver{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//private static String title="My Calories Consumed for last " + UIConstants.CHART_DAYS + " days";
	private static String title="My Daily Expense Summary";
	
	
	private CardHolder cardHolder = null;

	public UIExpenseSummary() {
		super(new BorderLayout());
		setBorder(BorderFactory.createTitledBorder(""));
		CardHolderDatabase.getInstance().addCardHolderDatabaseObserver(this);
	}
	
	
	
	public void loadExpenseChart(ExpenseProfile expenseProfile) {
		removeAll();
		add(new UIExpenseProfilePieChart(expenseProfile).getContentPane(),BorderLayout.NORTH);
		
		add(new UIExpenseProfileBarChart(expenseProfile).getContentPane(),BorderLayout.CENTER);
		repaint();
		revalidate();
	}
	
	
	@Override
	public void onLogin(CardHolder cardHolder, Integer familyId) {
		removeAll();
		this.cardHolder = cardHolder;
		cardHolder.getExpense().addExpenseProfileObserver(this);
		loadExpenseChart(cardHolder.getExpense());
		setBorder(BorderFactory.createTitledBorder("My Expense Summary"));
	}



	@Override
	public void onLogout(CardHolder cardHolder, Integer familyId) {
		this.cardHolder = null;
		removeAll();
		setBorder(BorderFactory.createTitledBorder(""));
	}
	@Override
	public void onUpdate(ExpenseProfile ExpenseProfile) {
		loadExpenseChart(ExpenseProfile);
		
	}
	
	
	
	private class UIExpenseProfilePieChart extends ApplicationFrame{
		
		
		public UIExpenseProfilePieChart(ExpenseProfile expenseProfile) {
                super(title);
                final DefaultPieDataset dataSet = createDataset(expenseProfile);
                final JFreeChart chart = createChart(dataSet);
                final ChartPanel chartPanel = new ChartPanel(chart);
                chartPanel.setPreferredSize(new java.awt.Dimension(500, 200));
                setContentPane(chartPanel);
        }

        private DefaultPieDataset createDataset(ExpenseProfile expenseProfile) {
        		DefaultPieDataset result = new DefaultPieDataset();
        		 result.setValue("Used", expenseProfile.getFundsUsed());
                   
        		result.setValue("Available", expenseProfile.getFundsAvailable());
        	    
                
               
                return result;
             
        }

        private JFreeChart createChart(final  PieDataset dataset) { 
        	      
        	JFreeChart chart = ChartFactory.createPieChart(
        	            "My Expense Summary",  // chart title
        	            dataset,                // data
        	            true,                   // include legend
        	            true,
        	            false
        	        );
        	    PiePlot plot = (PiePlot)chart.getPlot();
              plot.setSectionPaint(0, Color.RED);
              plot.setSectionPaint(1, Color.GREEN);
              return chart;
        }

	}
	
	
	private class UIExpenseProfileBarChart extends ApplicationFrame{
		
	
		public UIExpenseProfileBarChart(ExpenseProfile expenseProfile) {
                super(title);
                final CategoryDataset dataset = createDataset(expenseProfile);
                final JFreeChart chart = createChart(dataset);
                final ChartPanel chartPanel = new ChartPanel(chart);
                chartPanel.setPreferredSize(new java.awt.Dimension(500, 400));
                setContentPane(chartPanel);
        }

        private CategoryDataset createDataset(ExpenseProfile expenseProfile) {
        		 DefaultCategoryDataset result = new DefaultCategoryDataset();

        		 List<ExpenseEntry> expenseProfileEntries = expenseProfile.getExpenseEntries();
        		 int index = 0;
        		 if( expenseProfileEntries.size() > UIConstants.CHART_DAYS-1) {
                	index = expenseProfileEntries.size()-UIConstants.CHART_DAYS-1;
                }
        		 if(index < 0) {
     				index = 0;
     			}
        		ExpenseEntry todayExpenseEntry = null;
        		ExpenseEntry lastExpenseEntry = null;
                for(int i = index; i < expenseProfileEntries.size(); i++) {
                	ExpenseEntry expenseEntry = expenseProfileEntries.get(i);
                	Calendar dateDate = expenseEntry.getDate();
                	
                	String date = UIHelper.chartDateFormat.format(expenseEntry.getDate().getTime());
                	Calendar today = Calendar.getInstance();
                	if ((today.get(Calendar.DAY_OF_MONTH)==dateDate.get(Calendar.DAY_OF_MONTH)) && (today.get(Calendar.MONTH)==dateDate.get(Calendar.MONTH)) && (today.get(Calendar.YEAR)==dateDate.get(Calendar.YEAR))){
                    	 todayExpenseEntry = expenseEntry;
                    		
                    	} else {
                    		double con= expenseEntry.getAmount();
                    		result.addValue(con, "Used", date);
                    		 result.addValue(expenseEntry.getAvailable(), "Available", date);
                     		 
                    	}
                    
                  lastExpenseEntry = expenseEntry;
                }
                
                if(todayExpenseEntry == null) {
    				result.addValue(lastExpenseEntry.getAmount(), "Used", "Today");
    				result.addValue(expenseProfile.getFundsAvailable(), "Available", "Today");
    				
    				
    			} else {
    					  double con= todayExpenseEntry.getAmount();
    					  result.addValue(con, "Used", "Today");
                      	  result.addValue(expenseProfile.getFundsAvailable(), "Available", "Today");
                        	
                 }
                return result;
             
        }

        private JFreeChart createChart(final CategoryDataset dataset) { 
                final JFreeChart chart = ChartFactory.createBarChart(
                                title, "Days", "Expense", dataset,
                                PlotOrientation.VERTICAL, true, true, false);
               
                GradientPaint gradientpaint0 = new GradientPaint(0.0F, 0.0F,Color.GREEN, 0.0F, 04F,new Color(255,255,255));   
                GradientPaint gradientpaint1 = new GradientPaint(0.0F, 0.0F,Color.RED, 0.0F, 0.0F, new Color(255,255,255));  
//                GradientPaint gradientpaint2 = new GradientPaint(0.0F, 0.0F, new Color(205, 92, 92), 0.0F, 0.0F, new Color(136, 136, 255));  
//                      
                  
                BarRenderer r = (BarRenderer) chart.getCategoryPlot().getRenderer();  
                    r.setSeriesPaint(1, gradientpaint0);  
                  r.setSeriesPaint(0, gradientpaint1);  
//                    r.setSeriesPaint(2, gradientpaint2);   
                
                
                return chart;
        }

	}




	










	
}